<template>
	<div id="back_to_article_plan" v-loading="$store.state.saving"
				element-loading-text="保存中" element-loading-spinner="el-icon-loading"
				element-loading-background = "rgba(255,255,255,0.8)">
		<el-form :model="returnMon" ref="refReturnMon" :rules="returnMonRules" label-width="110px" class="demo-ruleForm" style="overflow:hidden">
			<el-form-item label="客户">
				<el-input disabled v-model="contract.customer.customerName"></el-input>
			</el-form-item>
			<el-form-item label="合同名称">
				<el-input disabled v-model="contract.contractNum"></el-input>
			</el-form-item>
			<el-form-item prop="returnDate" label="计划回款日期" class="inline__">
                <el-date-picker type="date" v-model="returnMon.returnDate" style="width:100%!important" placeholder="请选择回款日期" :picker-options="returnDatePicker"></el-date-picker>
			</el-form-item>
			<el-form-item label="期次" prop="returnTimes" class="inline__">
                <el-select v-model="returnMon.returnTimes" value-key="id" style="width:100%!important">
					<el-option v-for="item in returnTimes" :key="item.id" :label="item.name" :value="item" :disabled="!issue(item)"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="回款金额" prop="returnMoney" class="inline__">
                <el-input type="number" v-model="returnMon.returnMoney"></el-input>
			</el-form-item>
			<el-form-item label="未回款金额" prop="name" class="inline__">
                <el-input readonly v-model="surplus"></el-input>
			</el-form-item>
			<el-form-item label="负责人" prop="name" class="inline__">
                <el-select filterable v-model="returnMon.principal" value-key="empId" style="width:100%!important">
					<el-option-group v-for="d in  dept_emps" :key="d.departmentId" :label="d.departmentName">
						<el-option v-for="e in d.deEmp" :key="e.empId" :label="e.empName" :value="e"></el-option>
					</el-option-group>
				</el-select>
			</el-form-item>
            <el-form-item label="是否提醒" class="inline__">
                <el-radio-group :disabled="returnMon.isReturn == 1" v-model="returnMon.isReturn">
                    <el-radio v-if="returnMon.isReturn == 1" :label="1">已回款</el-radio>
                    <el-radio :label="2">提醒</el-radio>
                    <el-radio :label="3">不提醒</el-radio>
                </el-radio-group>
            </el-form-item>
			<el-form-item label="备注">
                <el-input type="textarea" v-model="returnMon.remark"></el-input>
			</el-form-item>
            <el-form-item>
				<el-button :disabled="returnMon.isReturn == 1" type="primary" @click="submitForm">保存</el-button>
				<el-button v-if="returnMon.returnId && returnMon.isReturn != 1" @click="deleteReturnmom" type="danger">删除</el-button>
				<el-button @click="$parent.$parent.backToArticlePlanDialogVisible = false">取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
export default {
	name: 'backToArticlePlan',
	props: ["contract"],
	data() {
		var validateMax = (rule, value, callback) => {
			if(!value || 0 == value){
				callback(new Error("请填写回款金额"))
			}
			if(value > this.maxReturnMoney){
				callback(new Error("回款金额最大为"+this.maxReturnMoney))
			}else if(value < 0){
				callback(new Error("金额必须大于0"))
			}else{
				callback()
			}
		}
		return {
			returnTimes:[],		// 回款期次
			dept_emps:[],
			returnMon:{			// 回款计划对象数据源
				principal:this.$store.state.user,
				isReturn:2,
                returnMoney:''
			},
			returnMonRules:{	// 表单验证规则
				returnMoney:[
					{ validator: validateMax, trigger: 'change' },
					{ required: true, message: '请填写回款金额', trigger: 'blur' },
				],
				returnTimes:[
					{ required: true, message: '请选择期次', trigger: 'change' }
				],
				returnDate:[
					{ required: true, message: '请选择回款日期', trigger: 'change' }
				]
			},
			returnmons:[],		// 传入的已存在的回款记录
			returnDatePicker:{
				disabledDate(time){
					return time.getTime() < Date.now() - 8.64e7
				}
			}
			
		}
	},
	methods:{
		// 初始化数据
		initData(){
			// 获取回款期次
			this.axios.get("api/dd/return_times")
			.then(res => {
				this.returnTimes = res.data
				console.log(this.returnTimes)
			})
			.catch(err => {
				
			})
			/* 获取部门员工列表 */
			this.axios.get("api/dept_emps")
			.then(res => {
				this.dept_emps = res.data
			})
			.catch(
				
			)
		},
		// 计算回款期次
		issue(rt){
			let flag = true
			this.returnmons.forEach(r => {
				if(r.returnTimes.id == rt.id){
					flag = false
				}
				
			})
			return flag
		},
		// 提交表单
		submitForm(){
			this.$refs.refReturnMon.validate((valide) => {
				if(valide){// 表单验证
					// 将合同对象赋值给returnMon
					this.returnMon.contract = this.contract
					// 发送请求
					this.$store.state.saving = true
					this.axios.post("api/in-sale/return-mon",this.returnMon)
					.then(async res => {
						await this.editConInvoice()
						this.$store.state.saving = false
						this.global.mes_success("回款计划保存成功")
						
						// 关闭弹窗
						this.$parent.$parent.backToArticlePlanDialogVisible = false
						// 判断是否从抽屉打开的
						if(this.isDrawer){
							this.$parent.$parent.$refs.contractDrawer.initData()
						}else{
							// 刷新
							this.$parent.$parent.initData()
						}
						
					})
					.catch(err => {
						this.$store.state.saving = false
						this.global.mes_error("回款计划保存失败，请稍后再试！")
						console.error(err); 
					})
				}else{
					this.global.mes_error("数据校验不通过，请修改后重新提交")
					return false
				}
			})
		},
		// 修改开票记录
		async editConInvoice(){
			// 判断是否由开票记录来的
			if(this.conInvoice){
                this.conInvoice.contract = this.contract
				this.conInvoice.isReturnMon = 1
				await this.axios.post("api/in-sale/conInvoice",this.conInvoice)
			}
		},
		// 删除,根据id删除
		deleteReturnmom(){
			this.global.confirm("提示！", "确认删除",()=>{
				this.axios.delete("api/in-sale/return-mon/"+this.returnMon.returnId)
				.then(res => {
					this.global.mes_success("删除成功")
					// 关闭弹窗
					this.$parent.$parent.backToArticlePlanDialogVisible = false
					// 刷新
					this.$parent.$parent.initData()
				})
			.catch(err => {
				this.global.mes_error("删除失败")
			})				
			}, ()=>{
				this.global.mes_message("取消删除")
			})

		}
	},
	created(){
		this.initData();
	},
	computed:{
		// 未回款金额的计算
		surplus(){
			return this.maxReturnMoney - parseInt(this.returnMon.returnMoney?this.returnMon.returnMoney:0)
		},
		// 最大回款金额的计算
		maxReturnMoney(){
			let totalReturn = 0
			this.returnmons.forEach(r => {
				if(r.returnId !== this.returnMon.returnId){
					totalReturn += parseInt(r.returnMoney?r.returnMoney:0)
				}
			});
			return this.contract.totalMoney- totalReturn
		}
	}
}
</script>

<style scoped>
#back_to_article_plan .el-form-item{width: 100%;margin-bottom: 22px !important;}
.inline__{width:50%!important;display:inline-block}
</style>